package com.myApp.view;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.myApp.db.Categorys;
import com.myApp.db.Channels;
import com.myApp.myfaverite.R;
import com.myApp.pojo.Channel;
import com.myApp.rss.RSSFeed;
import com.myApp.rss.RSSHandler;
import com.myApp.rss.RSSItem;

public class NewsSectionFragment extends Fragment implements OnItemClickListener {
	/**
	 * The fragment argument representing the section number for this
	 * fragment.
	 */
	public static final String ARG_SECTION_NUMBER = "section_number";

	public NewsSectionFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_view_dummy,
				container, false);
		
		// 新闻列表
		ListView news = (ListView) rootView
				.findViewById(R.id.listOfNews);
		
		ProgressBar progressBar = new ProgressBar(this.getActivity());
	    progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT, Gravity.CENTER));
	    progressBar.setIndeterminate(true);
	    
	    news.setEmptyView(progressBar);
		
	    // Must add the progress bar to the root of the layout
	    ViewGroup root = (ViewGroup) this.getActivity().findViewById(android.R.id.content);
	    root.addView(progressBar);
	    
	    List<Map<String, Object>> itemList = null;
	    
	    Categorys categorys = Categorys.getInstance(this.getActivity());
	    
	    //取得分类对应的RSS数据
	    itemList = this.getItemListOfCategory(categorys.get(getArguments().getInt(ARG_SECTION_NUMBER)).getCategoryId());
        
	    // SimpleAdapter参数，描述RSSItem的哪些内容将被显示在ListView上
	    String[] fromColumns = {RSSItem.TITLE, RSSItem.PUBDATE, RSSItem.CHANNEL};
	    
	    // SimpleAdapter参数，描述RSSItem内容将被显示在哪些控件上
	    int[] toViews = {R.id.title, R.id.pubDate, R.id.channel}; 
	    
	    SimpleAdapter mAdapter = new SimpleAdapter(this.getActivity(), itemList,
	            R.layout.news_item,
	            fromColumns, toViews);
	    
	    news.setAdapter(mAdapter);
	    news.setOnItemClickListener(this);
		
		return rootView;
	}
	
	/**
	 * 分类数据抽出
	 * 
	 * @param categoryId 分类ID
	 * 
	 * @return 供SimpleAdapter使用的RSS列表
	 */
	private List<Map<String, Object>> getItemListOfCategory(int categoryId){
		
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
		
		Channels channels = Channels.getInstance(this.getActivity());
		
		ArrayList<Channel> channelsOfCategory = channels.getChannelsOfCategory(categoryId);
		
		List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
		
		try {
			
			for (Channel channel : channelsOfCategory){
				
				URL url = new URL(channel.getChannelUri());
				
				InputStream  rsstream = url.openStream();
				
				//防止异常
				InputStreamReader isr = new InputStreamReader(rsstream, "GB2312");
				
		        SAXParserFactory factory = SAXParserFactory.newInstance();
		        SAXParser parser = factory.newSAXParser();
		        XMLReader reader = parser.getXMLReader();
		        
		        // 自定义捕捉器    
		        RSSHandler handler = new RSSHandler();
		        reader.setContentHandler(handler);
		        InputSource is = new InputSource(isr);
		        reader.parse(is);
		        
		        RSSFeed feed = handler.getFeed();
		        
		        List<Map<String, Object>> list = feed.getAllItemsForListView(channel.getChannelName());
		        
		        itemList.addAll(list);
			}
		
		} catch (MalformedURLException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			
			e.printStackTrace();
		} catch (SAXException e) {
			
			e.printStackTrace();
		}
		
		return itemList;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		String str = "arg0.getId={" + arg0.getId() + "}";

		Toast.makeText(this.getActivity(), str, 1);
	}
	
}